package com.example.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.example.common.enums.RoleEnum;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.mapper.BookMapper;
import com.example.mapper.OrdersItemMapper;
import com.example.mapper.OrdersMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrdersService {

    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private BookMapper bookMapper;
    @Resource
    private OrdersItemMapper ordersItemMapper;
    @Resource
    private CartService cartService;
    @Resource
    private UserService userService;

    public void add(Orders orders) {
        Account currentUser1 = TokenUtils.getCurrentUser();
        if (currentUser1.getScore()<50){
            throw new CustomException("500","信誉分低于50无法借阅");
        }
        List<Cart> cartList = orders.getCartList();
        //书单批量借阅
        if(CollUtil.isNotEmpty(cartList)){  //通过书单批量借阅
            String name="";
            int num=0;
            for (Cart cart : cartList) {
                Integer bookId = cart.getBookId();
                //根据id查询书的信息
                Book book = bookMapper.selectById(bookId);
                name += book.getName()+",";
                num += cart.getNum();    //总共借书的数量
                if (book == null){
                    throw new CustomException("500","图书不存在");
                }
                Integer store = book.getStore();
                if(cart.getNum() >store){
                    throw new CustomException("500","图书库存不足");
                }
            }
            name=name.substring(0,name.length()-1);
            name+= "等"+ num +"本书";
            orders.setName(name);

        }else{ //单个借阅
            //根据id查询书的信息
            Book book = bookMapper.selectById(orders.getBookId());
            if (book == null){
                throw new CustomException("500","图书不存在");
            }
            Integer store = book.getStore();
            if(orders.getNum() >store){
                throw new CustomException("500","图书库存不足");
            }
            orders.setName(book.getName());
        }
        //插入订单字段
        orders.setTime(DateUtil.now());
        Account currentUser = TokenUtils.getCurrentUser();
        orders.setUserId(currentUser.getId());
        orders.setStatus("借书待确认");
        orders.setOrderNo(IdUtil.getSnowflakeNextIdStr());  //唯一订单编号
        ordersMapper.insert(orders);

        //批量
        if(CollUtil.isNotEmpty(cartList)){
            for (Cart cart : cartList) {
               this.setOrderItem(orders,cart.getNum(),cart.getBookId());
               //借完书后批量删除书单(购物车)
                cartService.deleteById(cart.getId());
            }
        }else { //单个
            this.setOrderItem(orders,orders.getNum(),orders.getBookId());
        }

    }
    //插入ordersitem数据的封装方法
    public void setOrderItem(Orders orders,Integer num, Integer bookId){
        OrdersItem ordersItem = new OrdersItem();
        ordersItem.setOrderId(orders.getId());  //设置订单详情的订单id
        Book book = bookMapper.selectById(bookId);//根据不同的bookId参数查询图书详情
        ordersItem.setNum(num); //设置数量
        ordersItem.setBookCover(book.getCover());//设置封面
        ordersItem.setBookName(book.getName());//设置图书名称
        ordersItem.setBookId(bookId);//设置bookID
        ordersItemMapper.insert(ordersItem); //插入数据
    }

    public PageInfo<Orders> selectPage(Orders orders, Integer pageNum, Integer pageSize) {
        //用户只查询自己的订单
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())){
            orders.setUserId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Orders> list=ordersMapper.selectAll(orders);
        for (Orders order : list) {
            String time=order.getTime();
            long between=1+DateUtil.between(DateUtil.parseDate(time),new Date(), DateUnit.DAY);//计算借书时长(天)
            if(order.getStatus().equals("已借出")||order.getStatus().equals("还书待确认")){
                order.setDays(between);
            }
        }
        return PageInfo.of(list);
    }
    public Orders selectById(Integer id) {
        return ordersMapper.selectById(id);
    }
    public List<Orders> selectAll(Orders orders) {
        List<Orders> list=ordersMapper.selectAll(orders);
        return list;
    }

    public void updateById(Orders orders) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.ADMIN.name().equals(currentUser.getRole())){
            if("已借出".equals(orders.getStatus())){      //扣减库存
                List<OrdersItem> ordersItems = ordersItemMapper.selectByOrderId(orders.getId());
                for (OrdersItem ordersItem : ordersItems) {   //查询本次借的所以图书，依次扣减库存
                    Integer bookId = ordersItem.getBookId();
                    Book book = bookMapper.selectById(bookId);
                    Integer num = ordersItem.getNum();  //借书的数量
                    book.setStore(book.getStore()-num);
                    bookMapper.updateById(book); //更新库存
                }
            }
            if("已归还".equals(orders.getStatus())){    //加库存
                List<OrdersItem> ordersItems = ordersItemMapper.selectByOrderId(orders.getId());
                for (OrdersItem ordersItem : ordersItems) {   //查询本次借的所以图书，依次扣减库存
                    Integer bookId = ordersItem.getBookId();
                    Book book = bookMapper.selectById(bookId);
                    Integer num = ordersItem.getNum();  //借书的数量
                    book.setStore(book.getStore()+num);
                    bookMapper.updateById(book); //更新库存


                    // 超出30天扣除信誉分
                    String time =orders.getTime();
                    long between=1+DateUtil.between(DateUtil.parseDate(time),new Date(), DateUnit.DAY);//计算借书时长(天)
                    if(between>30){
                        Integer id = orders.getUserId();
                        User user = userService.selectById(id);
                        user.setScore(user.getScore()-10);
                        userService.updateById(user);
                    }
                }
            }
        }
        ordersMapper.updateById(orders);
    }

    public void deleteById(Integer id) {
        ordersMapper.deleteById(id);
    }

    public void deleteBatch(Integer[] ids) {
        for (Integer id : ids) {
            ordersMapper.deleteById(id);
        }
    }


}
